import { OnInit, Component, Output, EventEmitter, ViewChild, OnChanges } from '@angular/core';
import { FormGroup, NgForm, FormBuilder, Validators, FormControl, ValidationErrors } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { ClassService } from 'src/app/project/service/icm/icm-base/class/class.service';
import { ClassDTO } from 'src/app/project/model/icm/icm-base/class/class.dto';
import { FormUtil } from '@shared/utils/form-util';
import { OperationType, OperationNotification } from 'src/app/project/model/common/operation-notification';
import { Observable, Observer } from 'rxjs';
import { ProfessionService } from 'src/app/project/service/icm/icm-base/profession/profession.service';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { format } from 'date-fns';

@Component({
  selector: 'app-class-detail',
  templateUrl: './class-detail.component.html',
  styles: [],
})
export class ClassDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private classService: ClassService,
    private fb: FormBuilder,
    private professionService: ProfessionService,
  ) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required], [this.codeAsyncValidator]],
      name: ['', [Validators.required, Validators.pattern('[^ ]+')]],
      grade: ['', [Validators.required]],
      shortName: [''],
      showOrder: [0, [Validators.required]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<ClassDTO>>();

  /**
   * form组件
   */
  @ViewChild('classForm', { static: false })
  public classForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 专业信息
   */
  class: ClassDTO = {
    id: null,
    code: '',
    name: '',
    showOrder: 0,
    academyId: null,
    academyName: null,
    grade: null,
    professionId: null,
    professionName: null,
  };

  /**
   * 班级编码是否已存在，true为已存在
   */
  isExist: boolean;

  /**
   * 是否已选择专业
   */
  hasProfession = false;

  /**
   * 校验班级编码
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (!this.class.professionId) {
          observer.next({ error: true, noProfession: true });
          observer.complete();
          return;
        }
        this.classService
          .checkoutCodeIsExist(this.class.professionId, control.value ? control.value : '')
          .subscribe(data => {
            this.isExist = data.data;
          });
        if (this.isExist) {
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.classForm.form);
  }

  /**
   * 修改或新增班级信息
   * @param isPreView 是否预览
   * @param item 班级信息
   */
  edit(isPreView: boolean, item: ClassDTO) {
    this.isPreView = isPreView;

    this.class = this.initClass(item);
    this.isVisible = true;
  }

  /**
   * 初始化班级
   */
  initClass(item: ClassDTO): ClassDTO {
    return {
      id: item ? item.id : null,
      name: item ? item.name : '',
      code: item ? item.code : '',
      showOrder: item ? item.showOrder : 0,
      shortName: item ? item.shortName : null,
      grade: item ? item.grade : null,
      academyId: item ? item.academyId : null,
      academyName: item ? item.academyName : null,
      professionId: item ? item.professionId : null,
      professionName: item ? item.professionName : null,
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (!this.class.academyId) {
      this.msg.error('所属学院必选');
      return false;
    }
    if (!this.class.professionId) {
      this.msg.error('所属专业必选');
      return false;
    } else {
      this.professionService.findOnePage(this.queryOptions, null, null, this.class.academyId).subscribe(data => {
        if (data) {
          if (data.data.findIndex(item => item.id === this.class.professionId) === -1) {
            this.msg.error('所选专业不存在');
            return false;
          }
        }
      });
    }
    if (this.class.code === '') {
      this.msg.error('班级编码必填');
      return false;
    }
    if (this.class.grade === '') {
      this.msg.error('班级所属年级年份必填');
      return false;
    } else {
      this.class.grade = format(this.class.grade, 'YYYY');
    }
    if (this.class.name === '') {
      this.msg.error('班级名称必填');
      return false;
    }
    if (!this.class.showOrder && this.class.showOrder !== 0) {
      this.msg.error('显示顺序必填');
      return false;
    }
    return true;
  }

  /**
   * 保存
   */
  save() {
    // 验证表单
    if (!FormUtil.validateForm(this.classForm.form)) {
      this.msg.error('表单未验证通过');
      return;
    }
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.class.id) {
      // id为空，为新建
      this.classService.create(this.class).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.classService.complete(this.class.id, this.class).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: ClassDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {}
}
